#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
# @Time    : 2020/9/21 5:44 下午
# @Author  : HuiDong.Bai
# @Email   : huidong.bai@ximalaya.com
# @File    : SerialReader.py
# @Software: PyCharm
import os
import sys
import signal
import time
import serial
import serial.tools.list_ports
import platform


def quit_sys(signum, frame):
    ser.close()
    fp.close()
    print("ByeBye......")
    sys.exit(0)


def get_serial_com():
    if platform.system() == 'Windows':
        port_list = list(serial.tools.list_ports.comports())
        port_list_name = []
        if len(port_list) <= 0:
            print("串口设备为空，请检查!")
        else:
            for each_port in port_list:
                if "USB-SERIAL" in each_port[1]:
                    port_list_name.append(each_port[0])
        return port_list_name[0]
    else:
        return os.popen('ls /dev/tty.*usbserial*').readline().strip()


def get_serial(com_port):
    # 打开串口，并得到串口对象
    s = serial.Serial(com_port, '115200', timeout=4)
    # 判断是否打开成功
    if not s.is_open:
        s = -1
        print('打开串口失败')
        return s
    return s


if __name__ == '__main__':
    try:
        # 获取日志重定向位置，在桌面下创建logs文件夹，日志将存在该文件夹下
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        log_path = desktop_path + '/logs'
        if not os.path.exists(log_path):
            os.makedirs(log_path)

        ex_time = time.strftime('%Y-%m-%d-%H-%M', time.localtime(time.time()))

        com = get_serial_com()
        ser = get_serial(com)

        fp = open(f'{log_path}/RTOS_log_{ex_time}.txt', 'a+', encoding='UTF-8')

        signal.signal(signal.SIGINT, quit_sys)

        while True:
            line = ser.readline().strip()
            log = line.replace(b'\\\\x', b'%').decode("UTF-8", "ignore")

            if len(log):
                fp.write(log + '\r\n')
                print(log)

    except Exception as e:
        print("---异常---：", e)
